package com.ljh.util;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUpload {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
    public String fileUpload(String fileFileName,File file) throws IOException {
        String directory = simpleDateFormat.format(new Date());
        File dir=new File(ServletActionContext.getServletContext().getRealPath("upload")+"/"+directory);
        //判断文件是否上传，如果上传的话将会创建该目录
        if(!dir.exists()){
            dir.mkdir(); //创建该目录
        }
        String suffix = fileFileName.substring(fileFileName.lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        File newFile = new File(ServletActionContext.getServletContext().getRealPath("upload")+"/" + directory + newFileName);
        String url=ServletActionContext.getRequest().getScheme() + "://" + ServletActionContext.getRequest().getServerName() + ":" + ServletActionContext.getRequest().getServerPort() +ServletActionContext.getRequest().getContextPath()+"/upload/" + directory + newFileName;
        FileUtils.copyFile(file,newFile);
        return url;
    }
}
